﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Web.SessionState;
using SZHL.UI.AppCode;
using SZHL.Data;
using System.Data;
using System.IO;
using System.Net;
using System.Collections;

namespace SZHL.UI.API
{
    /// <summary>
    /// FTAPI 的摘要说明
    /// </summary>
    public class CommAPI : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";
            context.Response.ContentType = "text/plain";
            string strAction = context.Request["Action"] ?? "";
            // string strUserName = "";
            Msg_Result Model = new Msg_Result() { Action = strAction.ToUpper(), ErrorMsg = "" };
            string P1 = context.Request["P1"] ?? "";
            string P2 = context.Request["P2"] ?? "";
            if (!string.IsNullOrEmpty(strAction))
            {
                try
                {


                    //TODO: 未实现,分享页面的接口通过暂时将分享人的code传递给打开链接的人来调用接口(不安全)
                    if (strAction == "GETFOLDERBYCODE")
                    {
                        string strWhere = string.Format("sharecode='" + P1 + "' and sharepasd='" + P2 + "'").FilterSpecial();
                        string strSQLFLODER = string.Format(@"select * from FT_Folder  where 1=1 and  {0}   order by CRDate desc  ", strWhere);
                        DataTable dtFLODER = new FT_FolderB().GetDTByCommand(strSQLFLODER);

                        string strSQLFILE = string.Format(@"select  *  from FT_File  where 1=1  and  {0}   order by CRDate desc  ", strWhere);
                        DataTable dtFILE = new FT_FileB().GetDTByCommand(strSQLFILE);
                        Model.Result = dtFLODER;
                        Model.Result1 = dtFILE;
                    }
                    if (strAction == "GETSHARELIST")
                    {
                        Model.Result = new FT_FolderB().GetEntities(d => d.PFolderID.ToString() == P1);
                        Model.Result1 = new FT_FileB().GetEntities(d => d.FolderID.ToString() == P1);
                    }
                    if (strAction == "COMPRESSFOLDER")
                    {
                        string strCode = P1;
                        FT_FolderB.FoldFile Mode = new FT_FolderB.FoldFile();
                        Mode.FolderID = -1;
                        Mode.Name = "压缩文件";
                        Mode.SubFileS = new List<FT_File>();
                        Mode.SubFolder = new List<FT_FolderB.FoldFile>();
                        foreach (string item in P1.SplitTOList(','))
                        {
                            string strID = item.Split('|')[0].ToString();
                            string strType = item.Split('|')[1].ToString();
                            if (item.Split('|')[1].ToString() == "file")
                            {
                                FT_File file = new FT_FileB().GetEntity(d => d.ID.ToString() == strID);
                                Mode.SubFileS.Add(file);
                            }
                            else
                            {
                                List<FT_FolderB.FoldFileItem> ListID = new List<FT_FolderB.FoldFileItem>();
                                FT_FolderB.FoldFile obj = new FT_FolderB().GetWDTREE(int.Parse(strID), ref ListID);
                                Mode.SubFolder.Add(obj);
                            }
                        }
                        JH_Auth_QY QYinfo = new JH_Auth_QYB().GetEntities().FirstOrDefault();

                        IsoDateTimeConverter timeConverterys = new IsoDateTimeConverter();
                        timeConverterys.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                        string ResultYS = JsonConvert.SerializeObject(Mode, Formatting.Indented, timeConverterys).Replace("null", "\"\"");


                        Dictionary<String, String> DATA = new Dictionary<String, String>();
                        DATA.Add("data", ResultYS);

                        HttpWebResponse ResponseData = CommonHelp.CreatePostHttpResponse(QYinfo.FileServerUrl + "zipfolder", DATA, 0, "", null);

                        string strData = CommonHelp.GetResponseString(ResponseData);



                        Model.Result = strData;
                    }
                    else if (strAction == "AUTOSENDSMS") //自动发短信
                    {
                        string strSQLFILE = "select * from ZH_DXGL where isSend='N' and SendTime<getdate()";
                        DataTable dt = new ZH_DXGLB().GetDTByCommand(strSQLFILE);
                        foreach (DataRow dr in dt.Rows)
                        {
                            var tel = dr["dxnums"];
                            var con = dr["dxContent"];
                            if (tel != null && tel.ToString() != "" && con != null && con.ToString() != "")
                            {
                                CommonHelp.SendSMS(tel.ToString(), con.ToString());
                                string strSQLFILE1 = string.Format(@"update ZH_DXGL set isSend='Y' where ID='{0}'", dr["ID"].ToString());
                                new ZH_DXGLB().ExsSql(strSQLFILE1);
                            }
                        }
                    }
                    else if (strAction == "ADDDLS")//添加代理商
                    {
                        try
                        {
                            P1 = context.Request["data"] ?? "";

                            KZ_GYSGL gysgl = JsonConvert.DeserializeObject<KZ_GYSGL>(P1);
                            if (new JH_Auth_UserB().GetEntities(d => d.UserName == gysgl.Phone).ToList().Count > 0)
                            {
                                Model.ErrorMsg = "此手机已注册，请直接登陆";
                            }
                            else
                            {
                                gysgl.CRUser = gysgl.Email;
                                gysgl.CRDate = DateTime.Now;
                                new KZ_GYSGLB().Insert(gysgl);
                                JH_Auth_User user = new JH_Auth_User();
                                user.UserName = gysgl.Phone;
                                user.UserRealName = gysgl.LinkUser;
                                user.UserPass = CommonHelp.GetMD5("123");
                                user.telphone = gysgl.Phone;
                                user.IsUse = "Y";
                                user.BranchCode = 23;
                                user.zhiwu = "代理商";
                                user.mailbox = gysgl.Email;
                                new JH_Auth_UserB().Insert(user);
                                JH_Auth_UserRole userRole = new JH_Auth_UserRole();
                                userRole.UserName = user.UserName;
                                userRole.RoleCode = 19;
                                new JH_Auth_UserRoleB().Insert(userRole);
                                Model.Result = gysgl;
                                string strContent = new Random().Next(0, 100) + "企捷云用户代理商登录地址：http://oa.chinainternet.com.cn/";
                                strContent += "登录名：" + user.UserName;
                                strContent += "密码：123";
                                //发送短信
                                CommonHelp.SendSMS(gysgl.Phone, strContent);
                            }
                        }
                        catch (Exception ex)
                        {
                            Model.ErrorMsg = "添加失败，请重试";
                        }
                    }
                    else if (strAction == "ADDKHGL")//添加代理商
                    {
                        P1 = context.Request["data"] ?? "";
                        ZH_KHGL khgl = new ZH_KHGL();
                        khgl = JsonConvert.DeserializeObject<ZH_KHGL>(P1);
                        try
                        {
                            if (khgl.ID == 0)
                            {
                                khgl.CRDate = DateTime.Now;
                                khgl.CRUser = "297362076@qq.com";
                                new ZH_KHGLB().Insert(khgl);
                                Model.Result = khgl;
                            }
                        }
                        catch (Exception ex)
                        {
                            Model.ErrorMsg = "添加用户失败";
                        }
                    }
                    else if (strAction == "ADDUser")//添加代理商
                    {
                        P1 = context.Request["data"] ?? "";
                        JH_Auth_User user = new JH_Auth_User();
                        user = JsonConvert.DeserializeObject<JH_Auth_User>(P1);
                        user.UserName = user.mobphone;
                        user.IsUse = "Y";
                        user.BranchCode = 16;
                        List<JH_Auth_User> user1 = new JH_Auth_UserB().GetEntities(d => d.UserName == user.UserName || d.mobphone == user.UserName).ToList();
                        if (user1.Count > 0)
                        {
                            Model.ErrorMsg = "您的手机号已注册，请登录";
                            return;
                        }
                        user.UserPass = CommonHelp.GetMD5("123");
                        JH_Auth_UserRole userRole = new JH_Auth_UserRole();
                        userRole.UserName = user.UserName;
                        userRole.RoleCode = 3;
                        new JH_Auth_UserRoleB().Insert(userRole);
                        if (!new JH_Auth_UserB().Insert(user))
                        {
                            Model.ErrorMsg = "添加用户失败";
                        }
                        else
                        {
                            try
                            {
                                WXHelp.BranchMangner.WX_CreateUser(user);
                                Model.Result = user;
                                string strContent = new Random().Next(0, 100) + "企捷云用户登录地址：http://oa.chinainternet.com.cn/";
                                strContent += "登录名：" + user.UserName;
                                strContent += "密码：123";
                                //发送短信
                                CommonHelp.SendSMS(user.UserName, strContent);
                            }
                            catch (Exception ex)
                            {
                                new JH_Auth_UserB().Delete(user);
                                Model.ErrorMsg = "添加用户失败";
                            }
                        }
                        new QJY_IdentityB().Delete(d => d.Phone == user.UserName);
                    }
                    else if (strAction == "ADDPHCode")//添加验证码
                    {

                        P1 = context.Request["data"] ?? "";
                        if (new JH_Auth_UserB().GetEntities(d => d.UserName == P1 || d.mobphone == P1).ToList().Count > 0)
                        {
                            Model.ErrorMsg = "此手机已注册，请直接登录";
                        }
                        else
                        {
                            try
                            {

                                QJY_Identity identity = new QJY_Identity();
                                identity.Phone = P1;
                                identity.CRDate = DateTime.Now;
                                identity.IdentityCode = GetIdentity(6);
                                identity.CodeType = "";
                                new QJY_IdentityB().Insert(identity);
                                string content = "欢迎注册企捷云,您的验证码为：" + identity.IdentityCode + "。若未操作，请忽略此短信";
                                CommonHelp.SendSMS(P1, content);
                                Model.Result = identity;

                            }
                            catch (Exception ex)
                            {
                                Model.ErrorMsg = "系统异常，请重试";
                            }

                        }
                    }
                    else if (strAction == "ValidPHCode")//添加验证码
                    {
                        try
                        {
                            P1 = context.Request["phone"] ?? "";
                            P2 = context.Request["code"] ?? "";
                            QJY_Identity identity = new QJY_IdentityB().GetEntity(d => d.Phone == P1 && d.IdentityCode == P2);
                            Model.Result = identity != null ? identity.IdentityCode : "";
                        }
                        catch (Exception ex)
                        {
                            Model.ErrorMsg = "系统异常，请重试";
                        }
                    }
                    else if (strAction == "ValidUser")//添加验证码
                    {
                        try
                        {
                            P1 = context.Request["user"] ?? "";
                            P2 = context.Request["pass"] ?? "";
                            P2 = CommonHelp.GetMD5(P2);
                            int count = new JH_Auth_UserB().GetEntities(d => d.UserName == P1 && d.UserPass == P2 && d.IsUse == "Y").Count();
                            if (count == 0)
                            {
                                Model.ErrorMsg = "用户名或密码错误";
                            }
                        }
                        catch (Exception ex)
                        {
                            Model.ErrorMsg = "系统异常，请重试";
                        }
                    }
                    else if (strAction == "AUTOALERT") //发送提醒
                    {
                        
                        string strSQLFILE = "select * from ZH_TXSX where Status='0'";
                        DataTable dt = new ZH_DXGLB().GetDTByCommand(strSQLFILE);
                        if (dt.Rows.Count > 0)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                try
                                {
                                    bool canclose = false; //是否结束
                                    bool cansend = false;  //是否发送提醒
                                    bool upcount = false;  //是否更新次数
                                    switch (dr["TXType"].ToString())
                                    {
                                        case "0":  //立即发送
                                            {
                                                cansend = true;
                                                canclose = true;
                                                upcount = true;
                                            }
                                            break;
                                        case "1":  //仅一次
                                            {
                                                DateTime sd = DateTime.Parse(dr["Date"].ToString() + " " + dr["Hour"].ToString() + ":" + dr["Minute"].ToString() + ":00");
                                                if (DateTime.Now >= sd)
                                                {
                                                    cansend = true;
                                                    canclose = true;
                                                    upcount = true;
                                                }
                                            }
                                            break;
                                        case "2":  //每个工作日
                                            {
                                                DateTime sd = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + dr["Hour"].ToString() + ":" + dr["Minute"].ToString() + ":00");

                                                if ((DateTime.Now.DayOfWeek == DayOfWeek.Monday
                                                        || DateTime.Now.DayOfWeek == DayOfWeek.Tuesday
                                                        || DateTime.Now.DayOfWeek == DayOfWeek.Wednesday
                                                        || DateTime.Now.DayOfWeek == DayOfWeek.Thursday
                                                        || DateTime.Now.DayOfWeek == DayOfWeek.Friday
                                                        ) && DateTime.Now > sd &&( dr["LstSendTime"].ToString()=="" ||DateTime.Parse(dr["LstSendTime"].ToString()).ToString("yyyy-MM-dd")!=DateTime.Now.ToString("yyyy-MM-dd")))
                                                {
                                                    upcount = true;
                                                    if (dr["CFType"].ToString() == "1")
                                                    {
                                                        cansend = true;
                                                    }
                                                    else if (dr["CFType"].ToString() == "2")
                                                    {
                                                        if (Int32.Parse(dr["CFCount"].ToString()) > Int32.Parse(dr["ZXCount"].ToString()))
                                                        {
                                                            cansend = true;
                                                            
                                                        }
                                                        else
                                                        {
                                                            canclose = true;
                                                        }
                                                    }
                                                    else if (dr["CFType"].ToString() == "3")
                                                    {
                                                        if (DateTime.Now < DateTime.Parse(dr["CFJZDate"].ToString()))
                                                        {
                                                            cansend = true;
                                                        }
                                                        else
                                                        {
                                                            canclose = true;
                                                        }
                                                    }
                                                }

                                            }
                                            break;
                                        case "3":  //每天
                                            {
                                                DateTime sd = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + dr["Hour"].ToString() + ":" + dr["Minute"].ToString() + ":00");

                                                if ((DateTime.Now > sd && (dr["LstSendTime"].ToString() == "" || DateTime.Parse(dr["LstSendTime"].ToString()).ToString("yyyy-MM-dd") != DateTime.Now.ToString("yyyy-MM-dd"))))
                                                {
                                                    upcount = true;
                                                    if (dr["CFType"].ToString() == "1")
                                                    {
                                                        cansend = true;
                                                    }
                                                    else if (dr["CFType"].ToString() == "2")
                                                    {
                                                        if (Int32.Parse(dr["CFCount"].ToString()) > Int32.Parse(dr["ZXCount"].ToString()))
                                                        {
                                                            cansend = true;
                                                        }
                                                        else
                                                        {
                                                            canclose = true;
                                                        }
                                                    }
                                                    else if (dr["CFType"].ToString() == "3")
                                                    {
                                                        if (DateTime.Now < DateTime.Parse(dr["CFJZDate"].ToString()))
                                                        {
                                                            cansend = true;
                                                        }
                                                        else
                                                        {
                                                            canclose = true;
                                                        }
                                                    }
                                                }
                                            }
                                            break;
                                        case "4":  //自定义
                                            {
                                                string Days = dr["Days"].ToString();
                                                foreach (var d in Days.Split(','))
                                                {
                                                    if (getWkDays(d) == DateTime.Now.DayOfWeek)
                                                    {
                                                        DateTime sd = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + dr["Hour"].ToString() + ":" + dr["Minute"].ToString() + ":00");
                                                        if ((DateTime.Now > sd && (dr["LstSendTime"].ToString() == "" || DateTime.Parse(dr["LstSendTime"].ToString()).ToString("yyyy-MM-dd") != DateTime.Now.ToString("yyyy-MM-dd"))))
                                                        {
                                                            upcount = true;
                                                            if (dr["CFType"].ToString() == "1")
                                                            {
                                                                cansend = true;
                                                            }
                                                            else if (dr["CFType"].ToString() == "2")
                                                            {
                                                                if (Int32.Parse(dr["CFCount"].ToString()) > Int32.Parse(dr["ZXCount"].ToString()))
                                                                {
                                                                    cansend = true;
                                                                }
                                                                else
                                                                {
                                                                    canclose = true;
                                                                }
                                                            }
                                                            else if (dr["CFType"].ToString() == "3")
                                                            {
                                                                if (DateTime.Now < DateTime.Parse(dr["CFJZDate"].ToString()))
                                                                {
                                                                    cansend = true;
                                                                }
                                                                else
                                                                {
                                                                    canclose = true;
                                                                }
                                                            }
                                                        }
                                                    }



                                                }

                                            }
                                            break;
                                    }
                                    if (cansend)
                                    {
                                        bool smsg = false;
                                        bool swx = false;
                                        if (dr["Type"].ToString() == "0") //短信和微信
                                        {
                                            smsg = true;
                                            swx = true;
                                        }
                                        else if (dr["Type"].ToString() == "1")  //短信
                                        {
                                            smsg = true;
                                        }
                                        else if (dr["Type"].ToString() == "2") //微信
                                        {
                                            swx = true;
                                        }

                                        if (smsg)  //发短信
                                        {
                                            foreach (var m in dr["TXUser"].ToString().Split(','))
                                            {
                                                object u = new ZH_DXGLB().ExsSclarSql("select mobphone from JH_Auth_User where UserName='" + m + "'");
                                                if (u != null)
                                                {
                                                    CommonHelp.SendSMS(u.ToString(), dr["CRUserRealName"].ToString() + "给你添加了提醒\n" + dr["TXContent"].ToString());
                                                }
                                            }

                                        }
                                        if (swx) //发微信
                                        {
                                            Senparc.Weixin.QY.Entities.Article a = new Senparc.Weixin.QY.Entities.Article();
                                            a.Title = "日程提醒";

                                            a.Description = dr["CRUserRealName"].ToString() + "给你添加了提醒\n" + dr["TXContent"].ToString();
                                            a.Url = dr["WXLink"].ToString();

                                            WXHelp.SendTH(a, "grxx", 0, dr["TXUser"].ToString());
                                        }
                                    }
                                    if (upcount)
                                    {
                                        new ZH_DXGLB().ExsSql("update ZH_TXSX set ZXCount=isnull(ZXCount,0)+1,LstSendTime=getdate() where ID=" + dr["ID"].ToString());
                                    }
                                    if (canclose)
                                    {
                                        new ZH_DXGLB().ExsSql("update ZH_TXSX set Status='1' where ID=" + dr["ID"].ToString());
                                    }
                                }
                                catch { 
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Model.ErrorMsg = "操作异常，请重试";
                    Model.Result = ex.Message;
                }

            }
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string Result = JsonConvert.SerializeObject(Model, Formatting.Indented, timeConverter).Replace("null", "\"\"");
            context.Response.Write(Result);
        }
        /// <summary>
        /// 获取随机验证码
        /// </summary>
        /// <param name="num">循环的次数</param>
        /// <returns></returns>
        protected static string GetIdentity(int num)//生成数字随机数
        {
            ArrayList MyArray = new ArrayList();
            Random random = new Random();
            string str = null;

            while (num > 0)
            {
                int i = random.Next(1, 9);
                if (MyArray.Count < 6)
                {
                    MyArray.Add(i);
                }
                num -= 1;
            }
            for (int j = 0; j <= MyArray.Count - 1; j++)
            {
                str += MyArray[j].ToString();
            }

            return str;
        }
        private DayOfWeek getWkDays(string wk)
        {
            DayOfWeek dw = new DayOfWeek();
            switch (wk)
            {
                case "周一":
                    dw = DayOfWeek.Monday;
                    break;
                case "周二":
                    dw = DayOfWeek.Tuesday;
                    break;
                case "周三":
                    dw = DayOfWeek.Wednesday;
                    break;
                case "周四":
                    dw = DayOfWeek.Thursday;
                    break;
                case "周五":
                    dw = DayOfWeek.Friday;
                    break;
                case "周六":
                    dw = DayOfWeek.Saturday;
                    break;
                case "周日":
                    dw = DayOfWeek.Sunday;
                    break;
            }

            return dw;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}